package clients;

/*
This file is part of Open Grid Job Management System (OGJMS).

OGJMS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

OGJMS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with OGJMS.  If not, see <http://www.gnu.org/licenses/>.

The entire and newest source code can be found at http://code.google.com/p/ogjms/  
*/

import grid.stefan.namespaces.jobManagement.JobManagementService.GetJobManagerStatus;
import grid.stefan.namespaces.jobManagement.JobManagementService.GetJobStatus;
import grid.stefan.namespaces.jobManagement.JobManagementService.JobManagementPortType;
import grid.stefan.namespaces.jobManagement.JobManagementService.StartJobManager;
import grid.stefan.namespaces.jobManagement.JobManagementService.StopJobManager;
import grid.stefan.namespaces.jobManagement.JobManagementService.service.JobManagementServiceAddressingLocator;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;

import org.apache.axis.client.Stub;
import org.globus.axis.message.addressing.EndpointReferenceType;
import org.globus.axis.util.Util;
import org.globus.wsrf.encoding.ObjectDeserializer;
import org.globus.wsrf.impl.security.authentication.Constants;
import org.globus.wsrf.impl.security.authorization.NoAuthorization;
import org.globus.wsrf.impl.security.descriptor.ClientSecurityDescriptor;
import org.oasis.wsrf.lifetime.Destroy;
import org.xml.sax.InputSource;

public class JobManagementServiceProxyClass {
	
	static {
		Util.registerTransport();
	}
	
	JobManagementPortType jobManagementPort;
	String fileName = "";

	public JobManagementServiceProxyClass(String fileName) {
		this.fileName = fileName;
		getEndpointReference();
		
	}

	private void getEndpointReference() {
		try {

			JobManagementServiceAddressingLocator serviceLocator = new JobManagementServiceAddressingLocator();

			FileInputStream fileReader = new FileInputStream(fileName);

			EndpointReferenceType instanceEPR;
			instanceEPR = (EndpointReferenceType) ObjectDeserializer
					.deserialize(new InputSource(fileReader),
							EndpointReferenceType.class);
			fileReader.close();
			this.jobManagementPort = serviceLocator
					.getJobManagementPortTypePort(instanceEPR);

			setSecurity((Stub) this.jobManagementPort);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void startJobManager(String proxyFile, String rslFile) {
		try {

			String proxy = readFileAsString(proxyFile);
			String jobDescription = readFileAsString(rslFile);

			StartJobManager start = new StartJobManager();
			start.setProxy(proxy);
			start.setJobDescription(jobDescription);

			jobManagementPort.startJobManager(start);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void stopJobManager() {
		try {
			jobManagementPort.stopJobManager(new StopJobManager());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public int getJobManagerStatus() {
		try {
			return jobManagementPort
					.getJobManagerStatus(new GetJobManagerStatus());
		} catch (Exception e) {
			e.printStackTrace();
			return -2;
		}
	}

	public String getJobStatus() {
		try {
			return jobManagementPort.getJobStatus(new GetJobStatus());
		} catch (Exception e) {
			e.printStackTrace();
			return "EROARE" + e.getMessage();
		}
	}

	public void destroy() {
		try {
			boolean deleted = deleteFile(this.fileName);
			if (deleted) {
				jobManagementPort.stopJobManager(new StopJobManager());
				jobManagementPort.destroy(new Destroy());
				//System.out.println("Resursa a fost stearsa!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void setSecurity(Stub stub) {
		///String CLIENT_DESC = "clients/client-security-descriptor.xml";
		//((Stub) stub)._setProperty(Constants.CLIENT_DESCRIPTOR_FILE,
		//		CLIENT_DESC);
		
		ClientSecurityDescriptor desc = new ClientSecurityDescriptor();
		desc.setAuthz(new NoAuthorization());
		//desc.setSecConvAnonymous();
		desc.setGSISecureConv(Constants.SIGNATURE);
		((Stub) stub)._setProperty(Constants.CLIENT_DESCRIPTOR, desc);
	}

	private String readFileAsString(String filePath) throws java.io.IOException {
		StringBuffer fileData = new StringBuffer(1000);
		BufferedReader reader = new BufferedReader(new FileReader(filePath));
		char[] buf = new char[1024];
		int numRead = 0;
		while ((numRead = reader.read(buf)) != -1) {
			fileData.append(buf, 0, numRead);
		}
		reader.close();
		return fileData.toString();
	}

	private boolean deleteFile(String fileName) {

		// A File object to represent the filename
		File f = new File(fileName);

		// Make sure the file or directory exists and isn't write protected
		if (!f.exists()) {
			System.out
					.println("Delete: no such file or directory: " + fileName);
			return false;
		}

		if (!f.canWrite()) {
			System.out.println("Delete: write protected: " + fileName);
			return false;
		}

		// If it is a directory, make sure it is empty
		if (f.isDirectory()) {
			System.out.println("Delete: it is a directory.Please give a file");
			return false;
		}

		boolean success = f.delete();
		return success;

	}
}
